package net.oschina.esb.core.timer;

import net.oschina.esb.EsbConfigKey;
import net.oschina.esb.core.AbstractSpringBootRegister;
import net.oschina.esb.core.env.EsbContext;
import net.oschina.esb.util.ConvertUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

/**
 * 自动注册 TimerStarter，需要在配置文件中配置 util.timer.enabled=true 开启， 默认是不开启
 *
 * @author Arvin
 * @time 2018/3/1 19:57
 */
@Configuration
public class AutoTimerStarterSpringBootRegister extends AbstractSpringBootRegister {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, Environment environment, ApplicationContext applicationContext) {

        String enabledString = EsbContext.getAppProperty(environment, EsbConfigKey.SWITCH_TIMER, "false");

        boolean enabled = ConvertUtil.toBoolean(enabledString, false);

        if (enabled) {

            logger.info("注册 TimerStarter： " + TimerStarter.class);

            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(TimerStarter.class);
            beanDefinition.setScope(GenericBeanDefinition.SCOPE_SINGLETON);

            registry.registerBeanDefinition("timerStarter", beanDefinition);
        }
    }
}
